﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DauGiaApp.Models;
namespace DauGiaApp.Controllers
{
    public class CommentController : Controller
    {
        //
        // GET: /Comment/
        DauGiaEntities data = new DauGiaEntities();
        public bool IsRole(TaiKhoan tk, string actionName)
        {

            PhanQuyen pq = (from dspq in data.PhanQuyens where dspq.TenQuyen == actionName select dspq).SingleOrDefault();
            ChiTietPhanQuyen ctpq = (from ctpqs in data.ChiTietPhanQuyens where (ctpqs.MaLoaiTaiKhoan == tk.MaLoaiTaiKhoan) && (ctpqs.MaPhanQuyen == pq.MaPhanQuyen) select ctpqs).Single();
            if (ctpq != null)
                return true;
            return false;
        }
         
        public ActionResult Index()
        {
            
            return View();
        }
        [HttpPost] 
        
        public ActionResult DangComment(int masanpham, string noidung_comment)
        {
            TaiKhoan curTK = Session["user"] as TaiKhoan;
            if (curTK != null)
            {
                try
                {
                    if (IsRole(curTK, "DangComment"))
                    {
                        Comment cm = new Comment();

                        cm.MaSanPham = masanpham;
                        cm.MaTaiKhoan = 1;
                        cm.TaiKhoan = data.TaiKhoans.ToList().ElementAt(0);
                        cm.NgayComment = DateTime.Now;
                        cm.NoiDungComment = noidung_comment;
                        //cm.MaComment= new Random().Next(1000);

                        data.Comments.AddObject(cm);
                        data.SaveChanges();
                        return RedirectToAction("GetComment", cm);
                    }
                    else
                    {
                        // Hoac thong bao thui.
                        return RedirectToAction("Alert", "Home");
                    }
                }
                catch
                {
                    //Response.Write("<script>alert('bạn không có quyền');</script>");
                    return RedirectToAction("Alert", "Home");
                }



            }
            else
            {
                return Content("Bạn chưa đăng nhập");
            }
            return RedirectToAction("Index", "Home");
            
            
           
        }

        public ActionResult GetComment(Comment comment)
        {
            comment.TaiKhoan = data.TaiKhoans.ToList().ElementAt(0);
            //Comment comment =  data.Comments.ToList().Find(cm => cm.MaComment == maComment);
            return PartialView(comment);
        }

    }
}
